const express = require('express')
const path = require('path')
const compression = require('compression')
const history = require('connect-history-api-fallback')
const { createProxyMiddleware } = require('http-proxy-middleware')

// 创建express应用
const app = express()

// 启用gzip压缩
app.use(compression())

// 配置代理
const proxyTable = process.env.PROXY_CONFIG ? JSON.parse(process.env.PROXY_CONFIG) : {
  '/api': {
    target: 'http://localhost:3000',
    changeOrigin: true,
    pathRewrite: {
      '^/api': ''
    }
  }
}

// 应用代理配置
Object.keys(proxyTable).forEach(context => {
  const options = proxyTable[context]
  app.use(context, createProxyMiddleware(options))
})

// 启用history模式
app.use(history({
  verbose: true,
  rewrites: [
    {
      // 避免代理接口被重写
      from: new RegExp('^/api/.*$'),
      to: function(context) {
        return context.parsedUrl.pathname
      }
    }
  ]
}))

// 静态资源目录
const staticDir = path.join(__dirname, 'dist')
app.use(express.static(staticDir))

// 端口配置
const port = process.env.PORT || 8080

// 启动服务器
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`)
})

module.exports = app
